<?php
namespace app\admin\controller;

use think\Cache;
use think\Session;
use think\Db;
use think\Image;
use think\Log;
use OSS\OssClient;
use OSS\Core\OssException;
use app\service\Token;

class Kaitest1
{
    //扣减分配错误充值积分
    public function deduct()
    {
        return '程序执行过了';
        // 从 yaoqing_records 表中找出误分配的记录
        $wrongRecords = Db::name('yaoqing_records')
            ->where('content', 'like', '%平级奖励(补发)%') // 假设记录说明中包含 '平级奖励(补发)' 标识错误记录，你可以根据实际情况修改
            ->select();

        $totalRecords = count($wrongRecords);
        $successRecords = 0;
        $errorRecords = [];
        $totalDeductAmount = 0;  // 记录总共扣减的额度

        // 循环处理每条误分配记录
        foreach ($wrongRecords as $record) {
            $partnerId = $record['uid'];  // 合伙人ID
            $deductScore = $record['money'];  // 要扣除的积分/金额
            $totalDeductAmount += $deductScore;  // 累加扣减额度

            // 获取合伙人当前积分
            $partnerInfo = Db::name('user')->where('id', $partnerId)->field('score, name')->find();
            $originalScore = $partnerInfo['score'];  // 原积分
            $newScore = $originalScore - $deductScore;  // 新积分

            // 获取充值用户信息
            $rechargeUser = Db::name('user')->where('id', $record['source_uid'])->field('name')->find();
            $rechargeUserName = $rechargeUser ? $rechargeUser['name'] : '未知用户';

            // 开启事务，确保操作的一致性

            Db::startTrans();
            try {
                // 1. 插入扣减记录（类似于补发记录的插入方式）
                Db::name('yaoqing_records')->insert([
                    'uid'        => $partnerId,
                    'touid'      => $record['touid'],  // 充值用户ID
                    'source_uid' => $record['source_uid'],  // 来源用户ID
                    'content'    => "{$rechargeUserName}({$record['source_uid']})充值 {平级奖励}(分配错误扣减)",
                    'money'      => $deductScore,
                    'time'       => time(),
                    'type'       => 1,
                    'data'       => 1,
                    'order_id'   => '',
                    'balance'    => $newScore,  // 扣减后的积分余额
                    'show_money' => $deductScore // 显示为负值
                ]);

                // 2. 扣除 user 表中合伙人的积分
                Db::name('user')
                    ->where('id', $partnerId)
                    ->setDec('score', $deductScore);

                Db::commit();

                // 记录操作日志
                $this->logAction("已成功撤销合伙人 {$partnerId}({$partnerInfo['name']}) 的误分配积分 {$deductScore}，原积分 {$originalScore}，现积分 {$newScore}");
                $successRecords++;
            } catch (\Exception $e) {
                Db::rollback();

                // 记录错误日志
                $this->logAction("撤销合伙人 {$partnerId} 的误分配积分失败，错误：{$e->getMessage()}", true);
                $errorRecords[] = [
                    'partnerId' => $partnerId,
                    'errorMessage' => $e->getMessage()
                ];
            }
        }

        // 返回操作结果
        return json([
            'code' => 200,
            'message' => '误分配积分已成功撤销',
            'data' => [
                'total_records' => $totalRecords,
                'success_records' => $successRecords,
                'error_records' => $errorRecords,
                'errors' => count($errorRecords),
                'total_deduct_amount' => $totalDeductAmount  // 总共扣减的额度
            ],
            'log_path' => realpath(__DIR__ . '/deduction_log.txt')
        ]);
    }

// 记录日志的函数示例
    public function logAction($message, $isError = false)
    {
        $logFilePath = __DIR__ . '/deduction_log.txt';
        $logMessage = date('Y-m-d H:i:s') . ($isError? '【ERROR】' : '【INFO】') . ' ' . $message . PHP_EOL;
        file_put_contents($logFilePath, $logMessage, FILE_APPEND);
    }
}